import editForm from "../form.vue";
// import {handleTree} from "@/utils/tree";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import { usePublicHooks } from "../../hooks";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import {
  getScriptList,
  addScript,
  delScript,
  updateScript
} from "@/api/scripts";
import { h, onMounted, reactive, type Ref, ref, toRaw, watch } from "vue";
import { useUserStoreHook } from "@/store/modules/user";

export function useScript(treeRef: Ref) {
  const form = reactive({
    scriptName: ""
  });
  const curRow = ref();
  const formRef = ref();
  const dataList = ref([]);
  const originDataList = ref([]);
  const treeIds = ref([]);
  const treeData = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const isLinkage = ref(false);
  const treeSearchValue = ref();
  const switchLoadMap = ref({});
  const isExpandAll = ref(false);
  const isSelectAll = ref(false);
  const { switchStyle } = usePublicHooks();
  const treeProps = {
    value: "id",
    label: "title",
    children: "children"
  };
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const publicPath = import.meta.env.VITE_PUBLIC_PATH;
  const domain = import.meta.env.VITE_DOMAIN;
  const columns: TableColumnList = [
    {
      label: "剧本编号",
      prop: "id"
    },
    {
      label: "剧本封面",
      cellRenderer: scope => (
        <el-image style="width: 100px; height: 100px" src={scope.row.image} />
      )
    },
    {
      label: "剧本名称",
      prop: "scriptName"
    },
    {
      label: "作者",
      prop: "writer"
    },
    {
      label: "状态",
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.status}
          active-value={1}
          inactive-value={0}
          active-text="已上架"
          inactive-text="未上架"
          inline-prompt
          style={switchStyle.value}
          onChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "更新时间",
      prop: "createTime"
    },
    {
      label: "操作",
      fixed: "right",
      width: 310,
      slot: "operation"
    }
  ];

  function onChange({ row }) {
    ElMessageBox.confirm(
      `确认要 <strong> ${
        row.status === 0 ? "下架" : "上架"
      }</strong> <strong style='color:var(--el-color-primary)'>${
        row.scriptName
      }</strong> 吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        updateScript(row)
          .then(res => {
            if (res.code === "0000") {
              message(`${res.message}`, { type: "success" });
              onSearch(); // 刷新表格数据
            } else {
              message(`${res.message}`, { type: "error" });
            }
          })
          .catch(err => {
            message(`${err.message}`, { type: "error" });
          });
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleDelete(row) {
    delScript(row.id)
      .then(res => {
        if (res.code === "0000") {
          message(`删除成功`, { type: "success" });
        } else {
          message(`删除失败`, { type: "error" });
        }
      })
      .catch(err => {
        message(err, { type: "error" });
      });
    onSearch();
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    console.log(dataList.value);
    pagination.currentPage = 1;
    onSearch();
  }
  function handleCurrentChange(val: number) {
    dataList.value = originDataList.value;
    pagination.currentPage = val;
    // 计算当前页的数据索引范围
    const startIdx = (pagination.currentPage - 1) * pagination.pageSize;
    const endIdx = startIdx + pagination.pageSize;
    dataList.value = dataList.value.slice(startIdx, endIdx);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  async function onSearch(queryParam: object = {}) {
    loading.value = true;
    for (const key in form) {
      // 检查属性是否有值
      if (form[key]) {
        // 添加到 queryParam 对象中
        queryParam[key] = form[key];
      }
    }
    await getScriptList(toRaw(queryParam)).then(res => {
      if (res.code === "0004") {
        useUserStoreHook().logOut();
      } else {
        dataList.value = res.data?.list;
        originDataList.value = res.data?.list;
        pagination.total = res.data.total;
      }
    });

    // 等待 500 毫秒，确保界面有足够的时间渲染
    await new Promise(resolve => setTimeout(resolve, 500));

    // 关闭 loading 状态
    loading.value = false;
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  async function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}剧本`,
      props: {
        formInline: {
          id: row?.id ?? "",
          scriptName: row?.scriptName ?? "",
          image: row?.image ?? "",
          writer: row?.writer ?? "",
          banner: row?.banner ?? "",
          brief: row?.brief ?? "",
          status: row?.status ?? 0
        }
      },
      width: "25%",
      draggable: true,
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        FormRef.validate(valid => {
          if (valid) {
            console.log("curData", curData);
            // 表单规则校验通过
            if (title === "新增") {
              addScript(curData)
                .then(res => {
                  message(res.message, {
                    type: "success"
                  });
                })
                .catch(err => {
                  message(err.message, {
                    type: "error"
                  });
                });
              done(); // 关闭弹框
              onSearch(); // 刷新表格数据
            } else {
              updateScript(curData)
                .then(res => {
                  message(res.message, {
                    type: "success"
                  });
                  onSearch({}); // 刷新表格数据
                })
                .catch(err => {
                  message(err.message, {
                    type: "error"
                  });
                });
              done(); // 关闭弹框
            }
          }
        });
      }
    });
  }

  const onQueryChanged = (query: string) => {
    treeRef.value!.filter(query);
  };

  const filterMethod = (query: string, node) => {
    return transformI18n(node.title)!.includes(query);
  };

  onMounted(async () => {
    onSearch();
  });

  watch(isExpandAll, val => {
    val
      ? treeRef.value.setExpandedKeys(treeIds.value)
      : treeRef.value.setExpandedKeys([]);
  });

  watch(isSelectAll, val => {
    val
      ? treeRef.value.setCheckedKeys(treeIds.value)
      : treeRef.value.setCheckedKeys([]);
  });

  const editScript = row => {
    window.open(
      `${domain}${publicPath}#/game-edit?scriptId=${row.id}`,
      "_blank"
    );
  };

  return {
    form,
    isShow,
    curRow,
    loading,
    columns,
    dataList,
    treeData,
    treeProps,
    isLinkage,
    pagination,
    isExpandAll,
    isSelectAll,
    treeSearchValue,
    onSearch,
    resetForm,
    openDialog,
    handleDelete,
    filterMethod,
    transformI18n,
    onQueryChanged,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    editScript
  };
}
